<?php
namespace Business;
class UserModel{
    static public function login($loginname,$password){
        //$user = \UserModel::where('phone',$loginname)->orWhere('email',$loginname)->first();
        $user = \UserModel::where(function($query) use($loginname){
            $query->orWhere('phone',$loginname)
                ->orWhere('email',$loginname);
        })->first();
        if($user){
            if ($user->password !== $password) {
                return false;
            }

            $s = \WalletModel::where('user_id',$user->id)->first();
            if (!$s) {
                //初始化钱包
                static::initWallet($user->id);
            }

            $data = $user->toArray();
        }else{
            $data = array();
        }
        return $data;
    }
    static public function initWallet($user_id) {
        $s = \WalletModel::find($user_id);
        if (!$s) {
            //初始化钱包
            $ecoin = new \WalletModel();
            $ecoin->user_id = $user_id;
            $ecoin->type = 'ecoin';
            $ecoin->save();

            $point = new \WalletModel();
            $point->user_id = $user_id;
            $point->type = 'point';
            $point->save();
        }
    }
    static public function getUser($id = null){
        $user = \UserModel::where('id',$id)->first();
        if($user){
            $ret = $user->toArray();
        }else{
            $ret = array();
        }
        return $ret;
    }
    static public function searchUser($search = null){
        $user = \UserModel::orWhere('phone',$search)
            ->orWhere('email',$search)
            ->first();
        if($user){
            $ret = $user->toArray();
        }else{
            $ret = array();
        }
        return $ret;
    }
    static public function reg($params){
        $user = new \UserModel();
        foreach($params as $k =>$v){
            if(isset($params[$k]))
                $user->$k = $v;
        }
        if($user->save()){
            //初始化钱包
            static::initWallet($user->id);
            return $user->id;
        }else{
            return 0;
        }
    }
    static public function getCart($user_id){
        $res = \ProductModel::where('c.user_id',$user_id)
            ->join('cart as c','c.product_id','=','product.product_id');
        $res = $res->with('info');
        $res = $res->get();
        if($res){
            $ret = $res->toArray();
        }else{
            $ret = array();
        }
        return $ret;
    }
    static public function delFromCart($user_id,$product_id){
        !is_array($product_id) && $product_id = explode(',',$product_id);
        $res = \CartModel::where('user_id',$user_id)
            ->whereIn('product_id',$product_id);
        if ($res->delete()) {
            $ret = true;
        } else {
            $ret = false;
        }
        return $ret;
    }
    static public function addFavourite($user_id,$product_id){
        $res = \FavouriteModel::where('user_id',$user_id)
            ->where('product_id',$product_id)
            ->first();
        if($res){
            return true;
        } else {
            $res = new \FavouriteModel();
            $res->user_id = $user_id;
            $res->product_id = $product_id;
            if($res->save()){
                return true;
            }else{
                return false;
            }
        }
    }
    static public function getFavourite($user_id){
        $res = \ProductModel::where('f.user_id',$user_id)
            ->join('favourite as f','f.product_id','=','product.product_id');
        $res = $res->with('info');
        $res = $res->get();
        if($res){
            $ret = $res->toArray();
        }else{
            $ret = array();
        }
        return $ret;
    }
    static public function delFromFavourite($user_id,$product_id) {
        !is_array($product_id) && $product_id = explode(',',$product_id);
        $res = \FavouriteModel::where('user_id',$user_id)
            ->whereIn('product_id',$product_id);
        if($res->delete()){
            $ret = true;
        }else{
            $ret = false;
        }
        return $ret;
    }
    static public function getBook($user_id,$book_id) {
        $res = \BookModel::where('book.book_id',$book_id)
            ->where('ub.user_id',$user_id)
            ->join('user_book as ub','ub.book_id','=','book.book_id');
        $res = $res->first();
        if($res){
            $ret = $res->toArray();
        }else{
            $ret = array();
        }
        return $ret;
    }
    static public function getBookList($user_id) {
        $res = \BookModel::select('book.book_id','book.name','book.author','book.cover_front','book.version')
            ->where('ub.user_id',$user_id)
            ->join('user_book as ub','ub.book_id','=','book.book_id');
        $res = $res->get();
        if($res){
            $ret = $res->toArray();
        }else{
            $ret = array();
        }
        return $ret;
    }
    static public function delFromShelves($user_id,$book_id) {
        $book_id = explode(',',$book_id);
        $res = \UserBookModel::where('user_id',$user_id)
            ->whereIn('book_id',$book_id);
        if($res->delete()){
            $ret = true;
        }else{
            $ret = false;
        }
        return $ret;
    }
    static public function createOrder($user_id,$items){
        \DB::beginTransaction();
        $order = new \OrderModel();
        $order->user_id = $user_id;
        $pay_total = 0;
        $order_type = 1;
        $pids = array();
        foreach($items as &$v) {
            //自动计算价格 标准价格 促销价格
            $price = ProductModel::getProductPrice($v['product_id'],$v['product_discount_id']);
            if ($price === null) {
                //没有找到价格记录则 删除此件商品
                unset($v);
                continue;
            }
            $v['price'] = $price;
            $pay_total += $v['price'] * $v['quantity'];
            array_push($pids,$v['product_id']); //推入pids数组最后用来删除购物车中的记录
        }
        $order->pay_total = $pay_total;
        if (!$order->save()) {
            return false;
        }
        foreach ($items as &$v) {
            $v['order_id'] = $order->order_id;
            $v['user_id'] = $user_id;
        }
        //添加产品明细
        $op = \DB::table('order_product')->insert($items);
        if ($op <= 0) {
            \DB::rollback();
            return false;
        }
        //删除购物车中的
        $res = static::delFromCart($user_id,$pids);
        if (!$res) {
            //\DB::rollback();
            // 删除失败这里不回滚
        }
        \DB::commit();
        return $order->where('order_id',$order->order_id)->first()->toArray();
    }
    static public function getOrder($user_id, $order_id){
        $order = new \OrderModel();
        $order = $order->where('order_id',$order_id);
        $order = $order->where('user_id',$user_id);
        $order = $order->first();
        if($order){
            $ret = $order->toArray();
        }else {
            $ret = array();
        }
        return $ret;
    }

    static public function setOrder($user_id,$order_id,$data){
        $order = new \OrderModel();
        $order->where('order_id',$order_id)->first();
        foreach($data as $k=>$v){
            $order->$k = $v;
        }
        if($order->save()){
            $ret = $order->toArray();
        }else {
            $ret = array();
        }
        return $ret;
    }
    //支出
    static public function outlay($user_id,$carry_fee,$type ='ecoin',$out_trade_no = '',$remark = ''){
        $wallet = \WalletModel::where('user_id',$user_id)->where('type',$type)->first();
        if(!$wallet || $wallet->total < $carry_fee){
            //钱包不足或者不存在钱包
            return false;
        }
        $last_remain  = $wallet->total;
        $wallet->decrement('total',$carry_fee);
        $saveW = $wallet->save();
        if ($saveW) {
            $bill = new \BillModel();
            $bill->user_id      = $user_id;
            $bill->type         = $type;
            $bill->balance      = 'outlay';
            $bill->carry        = $carry_fee;
            $bill->remain       = $wallet->total;
            $bill->last_remain  = $last_remain;
            $bill->out_trade_no  = $out_trade_no;
            $bill->remark       = $remark;
            $saveB = $bill->save();
        }
        if($saveW && $saveB){
            return true;
        }else{
            return false;
        }
    }
    //收入
    static public function income($user_id,$carry_fee,$type ='ecoin',$out_trade_no = '',$remark = ''){
        $wallet = \WalletModel::where('user_id',$user_id)->where('type',$type)->first();
        if(!$wallet){
            //不存在钱包
            return false;
        }
        $last_remain  = $wallet->total;
        $wallet->increment('total',$carry_fee);
        $saveW = $wallet->save();
        if ($saveW) {
            $bill = new \BillModel();
            $bill->user_id      = $user_id;
            $bill->type         = $type;
            $bill->balance      = 'income';
            $bill->carry        = $carry_fee;
            $bill->remain       = $wallet->total;
            $bill->last_remain  = $last_remain;
            $bill->out_trade_no  = $out_trade_no;
            $bill->remark       = $remark;
            $saveB = $bill->save();
        }
        if($saveW && $saveB){
            return true;
        }else{
            return false;
        }
    }
    //评论列表
    static public function getCommentList($user_id,$per_page=10) {
        $res = \CommentModel::select(array('comment.*','nickname','realname'));
        $res = $res->join('user as u','u.id','=','comment.user_id');
        $res = $res->where('comment.user_id',$user_id);
        $res = $res->paginate($per_page);
        if($res){
            $page= $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        return $data;
    }
    static public function getWallet($user_id) {
        $wallet = \WalletModel::where('user_id',$user_id)->get();
        if (!$wallet) {
            return array();
        }
        $data = $wallet->toArray();
        $ret = array();
        foreach ($data as $v) {
            $ret[$v['type']]['id'] = $v['id'];
            $ret[$v['type']]['total'] = $v['total'];
            $ret[$v['type']]['updated_at'] = $v['updated_at'];
        }
        return $ret;
    }
    //账单列表
    static public function getBillList($user_id,$per_page=10) {
        $res = \BillModel::where('user_id',$user_id);
        $res = $res->paginate($per_page);
        if($res){
            $page= $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        return $data;
    }
    //订单列表
    static public function getOrderList($user_id,$pay_status = null,$per_page = 10) {
        $res = \OrderProductModel::select(array(
            'pi.name',
            'pi.product_id',
            'order_product.order_product_id',
            'order_product.order_id',
            'order_product.price',
            'order_product.quantity',
            'order_product.quantity',
            'o.*',
        ));
        $res = $res->where('order_product.user_id',$user_id);
        $res = $res->with('field');
        $res = $res->leftJoin('order as o','order_product.order_id','=','o.order_id');
        $res = $res->where('o.order_type',1);
        if( !is_null($pay_status)) {
            $res = $res->where('o.pay_status',$pay_status);
        }
        $res = $res->leftJoin('product_info as pi','order_product.product_id','=','pi.product_id');
        $res = $res->paginate($per_page);
        if($res){
            $page= $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        return $data;
    }
    static public function getGiftcardList($user_id,$is_use = null,$is_expire = null,$per_page = 10) {
        $res = \GiftcardModel::where('belong_user_id',$user_id);
        if (!is_null($is_use)) {
            $res = $res->where('is_use',$is_use);
        }
        if( !is_null($is_expire)) {
            if ($is_expire == 0) {
                $res = $res->where('expire_at','>=',date('Y-m-d H:i:s'));
            } else {
                $res = $res->where('expire_at','<=',date('Y-m-d H:i:s'));
            }
        }
        $res = $res->paginate($per_page);
        if($res){
            $page= $res->toArray();
            $data['data']= $page['data'];

            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        return $data;
    }
    //充值卡充值券充值封装
    static public function inpourFromGiftcard($user_id,$code,$type = 'C') {
        $res = \GiftcardModel::where('code',$code);
        //B类充值
        if ($type  === 'B') {
            $res = $res->where('belong_user_id',$user_id);
            $remark = '充值券充值';
        } else {
            $remark = '充值卡充值';
        }
        $res = $res->where('is_use',0);
        $res = $res->where('expire_at','>=',date('Y-m-d H:i:s'));
        $res = $res->first();
        if(!$res){
            return null;   //不存在优惠劵
        }
        $data = $res->toArray();
        $res->is_use = 1;
        $res->use_user_id = $user_id;
        \DB::beginTransaction();
        $s = $res->save();
        $i = static::income($user_id,$data['total'],'ecoin',$data['giftcard_id'],$remark);
        if ($s && $i) {
            \DB::commit();
            return true;
        } else {
            \DB::rollback();
            return false;
        }
    }
    static public function inpourFromThirdparty($user_id,$money,$pay_type = 'alipay'){
        $order = new \OrderModel();
        $order->user_id = $user_id;
        $order->order_type = 2;
        $order->pay_type = $pay_type;
        $order->pay_total = $money;
        if ($order->save()) {
            $out_trade_no = $order->id;
            if ($pay_type) {
                $notify_url = 'http://'.$_SERVER['HTTP_HOST'].'/Api/alipay/notify';
            } else {
                $notify_url = 'http://'.$_SERVER['HTTP_HOST'].'/Api/wxpay/notify';
            }
            $ret = array(
                'out_trade_no' => $out_trade_no,
                'total_fee' => $money,
                'notify_url' => $notify_url,
            );
        } else {
            $ret = null;
        }
        return $ret;
    }
    static public function addFriend($user_id,$friend_id,$friend_search = null) {
        if ( $friend_search && !$friend_id) {
            $friend = static::searchUser($friend_search);
        } else {
            $friend = static::getUser($friend_id);
        }
        if (!$friend) {
            return 0;
        }
        $friend_id = $friend['id'];
        try {
            $res = new \UserFriendModel();
            $res->user_id = $user_id;
            $res->friend_id = $friend_id;
            if($res->save()){
                //自动加好友
                if ($res->friend_id ==1) {
                    $res = new \UserFriendModel();
                    $res->user_id = 1;
                    $res->friend_id = $user_id;
                    $res->save();
                }
                return 1;
            }else{
                return 0;
            }
        } catch(\PDOException $e) {
            if ($e->getCode() == 23000) {
                return 2;
            }else {
                return 0;
            }
        }
    }
    static public function friend($user_id,$friend_nickname = null) {
        \DB::connection()->enableQueryLog();
        $res = new \UserFriendModel();
        $res = $res->select(array('u.nickname','user_friend.friend_id','uf.created_at','uf.updated_at'));
        $res = $res->where('user_friend.user_id',$user_id);
        if ($friend_nickname) {
            $res = $res->where('u.nickname','like','%'.$friend_nickname.'%');
        }
        $res = $res->join('user_friend as uf', function($join) {
            $join->on('user_friend.friend_id','=','uf.user_id')->on('user_friend.user_id', '=', 'uf.friend_id');
        });
        $res = $res->join('user as u','u.id','=','user_friend.friend_id');
        $res = $res->get();
        error_log(print_r($res->toArray(), true), 3, '/tmp/debug.log');
        error_log(print_r(\DB::getQueryLog(), true), 3, '/tmp/debug.log');

        if ($res) {
            $data = $res->toArray();
        } else {
            $data = array();
        }
        return $data;
    }
    static public function tellToFriend($from_user_id,$to_user_id,$product_id) {
        $res = new \MessageModel();

        $res->from_user_id = $from_user_id;
        $res->to_user_id = $to_user_id;
        $res->type = 1;
        $tmp = "您的好友%s给您推荐《%s》，点击书名立即查看";
        if (!$product_id) {
            return null;
        }
        $pi = \ProductInfoModel::where('product_id',$product_id)->first();
        if (!$pi) {
            return null;
        }
        $friend = \UserModel::where('id',$to_user_id)->first();
        if (!$friend) {
            return null;
        }
        $res->content = sprintf($tmp,$friend->nickname,$pi->name);
        $msg = array(
            'product_id' =>$product_id,
        );
        $res->json = json_encode($msg);
        if($res->save()){
            return true;
        }else {
            return false;
        }
        return $ret;
    }
    static public function message($user_id,$type=null,$per_page=10){
        $res = new \MessageModel();
        $res = $res->where('to_user_id',$user_id);
        if (!is_null($type)) {
            $res = $res->where('type',$type);
        }
        $res = $res->paginate($per_page);
        if($res){
            $page= $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        return $data;
    }
}
